<template>
  <div>
    <el-form ref="deptForm" label-width="120px" :model="form" :rules="formRules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:90%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:90%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:90%" placeholder="请选择">
          <el-option v-for="item in list" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:90%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="$emit('cancel')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeesSimples } from '@/api/employees'
import { addDepartments, getDepartmentsDetail, updateDepartments } from '@/api/departments'
export default {
  props: {
    originList: {
      type: Array,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    // 自定义校验, 校验code是否已存在
    const validCode = (rule, value, callback) => {
      // console.log(this.originList)
      // 获取一个只有code的新数组
      let existCode = this.originList.map(item => item.code)
      console.log(existCode)
      // 在编辑下, 解决code未修改, 失去焦点后也会提示
      if (this.isEdit) {
        existCode = this.originList.filter(item => item.id !== this.id).map(item => item.code)
        console.log(existCode)
      }
      // 判断是否已经存在
      if (existCode.includes(value)) {
        // 已经存在, 校验失败
        callback(new Error('该部门编码已经存在'))
      } else {
        callback()
      }
    }
    // 自定义校验, 校验同级部门名称是否存在
    const validName = (rule, value, callback) => {
      let existName = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      console.log(existName)
      // 编辑下, 不能在同级存在相同名字部门
      if (this.isEdit) {
        // 同级的pid相同, 获取pid
        const pid = this.originList.find(item => item.id === this.id).pid
        console.log(pid)
        // 获取到所有pid相同的
        const brother = this.originList.filter(item => item.pid === pid)
        console.log(brother)
        // 排除自己
        existName = brother.filter(item => item.id !== this.id).map(item => item.name)
        console.log(existName)
      }
      // 判断是否已经存在
      if (existName.includes(value)) {
        // 已经存在, 校验失败
        callback(new Error('该部门名称已经存在同级'))
      } else {
        callback()
      }
    }
    return {
      // 存储部门负责人信息
      list: [],
      // 收集表单数据对象
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 验证规则
      formRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1~50的部门名称', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1~50的部门编码', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 30, message: '请输入1~50的部门介绍', trigger: 'blur' }
        ]
      }
    }
  },
  // 方法三 倾听组件内props中属性或者data函数中属性的变化
  // watch: {
  //   id: function(newVal, oldVal) {
  //     console.log(newVal, oldVal)
  //     this.loadDepartmentsDetail()
  //   }
  // id: {
  //   handler(newVal, oldVal) {
  //     console.log(newVal, oldVal)
  //   },
  //   immediate: true // 页面一加载就会立即执行一次
  // }
  // }
  created() {
    this.loadEmployeesSimples()
    if (this.isEdit) {
      this.loadDepartmentsDetail()
    }
  },
  methods: {
    // 解决数据不更新问题第三种方法存在的问题解决(校验问题)
    // 父组件里弹层的close事件, 触发后触发this.$refs.addOrEditRefs.resetForm()调用子组件中下面方法重置表单
    // resetForm() {
    //   this.$refs.deptForm.resetFields()
    //   this.form = {
    //        name: '',
    //        code: '',
    //        manager: '',
    //        introduce: ''
    //        }
    // },
    // 根据id查询部门详情
    async loadDepartmentsDetail() {
      try {
        const res = await getDepartmentsDetail(this.id)
        console.log('getDepartmentsDetail', res)
        // 渲染获取的数据
        this.form = res.data
      } catch (error) {
        console.log('error', error)
      }
    },
    // 获取部门负责人信息
    async loadEmployeesSimples() {
      try {
        const res = await getEmployeesSimples()
        console.log('getEmployeesSimples', res)
        // 保存到data函数中
        this.list = res.data
      } catch (error) {
        console.log('error', error)
      }
    },
    // 新增部门
    async doAdd() {
      try {
        // 发送请求
        const res = await addDepartments({ ...this.form, pid: this.id })
        console.log(res)
        // 提示信息
        if (!res.success) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 渲染页面 - 子传父
        // 关闭弹层
        this.$emit('success')
      } catch (error) {
        console.log('error', error)
      }
    },
    // 编辑部门
    async doEdit() {
      try {
        await updateDepartments(this.form)
        // 重新渲染
        // 关闭弹层
        this.$emit('success')
      } catch (error) {
        console.log('error', error)
      }
    },
    // 新增部门
    hSubmit() {
      // 兜底校验
      this.$refs.deptForm.validate(valid => {
        if (!valid) return // 校验失败
        // 调用函数, 发送请求
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    }

  }
}
</script>

<style>

</style>
